import { HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AdminApiService } from 'src/app/api/admin-api.service';
import { UserControlApiService } from 'src/app/api/user-control-api.service';
import { Userinfo } from 'src/app/model/userInfo';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.less', '../../../styles/container.css']
})
export class AdminComponent implements OnInit {

  searchForm: FormGroup;
  adminInfoForm: FormGroup;
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  adminList: Array<Userinfo> = new Array();
  tableLoading = false;
  isInfoVisible = false;
  inforFormTitle = '添加用户';
  activateStatusLoadingStatus: Map<number, boolean> = new Map();


  constructor(
    private fb: FormBuilder,
    private adminApi: AdminApiService,
    private message: NzMessageService,
    private userApi: UserControlApiService,
  ) {
    this.searchForm = fb.group({
      adminName: []
    });
    this.adminInfoForm = fb.group({
      id: [],
      username: [],
      password: [],
      icon: [],
      nickName: [],
      note: [],
      // realName: [],
      email: [],
      // activateStatus: [],
      status: [],
    })
  }

  ngOnInit(): void {
    this.getUserInfoFromSever()
  }

  onSubmit() {
    this.getUserInfoFromSever();
  }

  handleDelete(id: number) {
    this.adminApi.delete([id]).subscribe(
      response => {
        this.message.success('用户删除成功');
        this.getUserInfoFromSever();
      },
      err => {
        this.message.error('删除用户错误');
        console.error(err);

      }
    )
  }

  cancelDelet() {

  }

  handleEdit(userInfo: Userinfo) {
    this.inforFormTitle = '编辑用户';
    this.isInfoVisible = true;
    this.setFormValue(userInfo);
  }

  handleAdd() {
    this.inforFormTitle = '添加用户';
    this.isInfoVisible = true;
  }

  handleCancel() {
    this.adminInfoForm.reset();
    this.isInfoVisible = false;
  }

  handleModalOk() {
    let adminId = this.adminInfoForm.controls['id'].value;
    if (adminId) {
      this.handleEditAdmin(this.adminInfoForm.value)
    } else {
      this.handleAddAdmin(this.adminInfoForm.value)
    }
  }

  handlePageIndexChange() {
    this.getUserInfoFromSever()
  }

  handlePageSizeChange() {
    this.getUserInfoFromSever()
  }

  handleAsiganRole(id: number) {

  }



  private setFormValue(userInfo: Userinfo) {
    for (const key in userInfo) {
      if (Object.prototype.hasOwnProperty.call(userInfo, key)) {
        if (this.adminInfoForm.contains(key)) {
          this.adminInfoForm.controls[key].setValue(userInfo[key]);
        }

      }
    }
  }

  private getUserInfoFromSever() {
    this.tableLoading = true;
    let params = new HttpParams({
      fromObject: {
        'pageNum': this.pageIndex.toString(),
        'pageSize': this.pageSize.toString()
      }
    })
    const keywordValue = this.searchForm.get('adminName')
    if (keywordValue.value) {
      params = params.append('keyword', keywordValue.value)
    }
    this.adminApi.list(params).subscribe(
      response => {
        this.tableLoading = false;
        this.adminList = response.list;
        this.total = response.total,
          console.log(response);
      },
      err => {
        this.message.error('服务器错误');
        this.tableLoading = false;
        console.error('服务器错误');
      }
    )
  }

  private handleAddAdmin(userInfo: Userinfo) {
    this.userApi.regist(userInfo).subscribe(
      respones => {
        this.message.success("添加用户成功");
        this.handleCancel();
        this.getUserInfoFromSever();
      },
      err => {
        this.message.error("添加用户错误");
        console.error(err);
      }
    )

  }

  private handleEditAdmin(userInfo: Userinfo) {
    this.adminApi.update(userInfo.id, userInfo).subscribe(
      respones => {
        this.message.success("编辑用户成功");
        this.handleCancel();
        this.getUserInfoFromSever();
      },
      err => {
        this.message.error("编辑用户错误");
        console.error(err);
      }
    )

  }


}
